import re
import wx
import firebrick
import logging
import wx.lib.agw.aui as aui

class Perspective(object):
    '''Object that represents a perspective
    
    The main reason this exists is to encapsulate the 
    function that gets a list of all panels in a perspective.
    '''

    def __init__(self, name, aui_perspective_info="", protected=False):
        '''If protected is True, don't allow this to be renamed or deleted'''
        self.protected = protected
        self.info = aui_perspective_info
        self.name = name
        self.id = wx.NewId()

    @property
    def panes(self):
        result = []
        if self.info[0:8] == "layout2|":
            for panelinfo in self.info[8:].split("|"):
                if panelinfo.startswith("name="):
                    ppi = PartialPaneInfo(panelinfo)
                    if ppi.IsShown():
                        result.append(ppi.name)
        else:
            logging.getLogger().warning("unsupported perspective format")
        return result

class PerspectiveAlreadyExistsError(Exception):
    def __init__(self, value="Perspective already exists"):
        self.value = value
    def __str__(self):
        return repr(self.value)

class PartialPaneInfo(aui.AuiPaneInfo):
    # it would be really, really nice if we could use the LoadPaneInfo
    # method of the AuiManager object, but it's buggy. For example,
    # it seems to require that a best_size attribute is set before I
    # can load data. Likewise for a few other attributes. Since I only
    # need a couple bits of information, we'll roll our own. 
    def __init__(self, panelinfo):
        self.panelinfo = panelinfo
        super(PartialPaneInfo, self).__init__()
        for field in panelinfo.split(";"):
            match = re.match("(name|state)=(.*)$", field)
            if match:
                if match.group(1) == "state":
                    self.state = int(match.group(2))
                elif match.group(1) == "name":
                    self.name = match.group(2)
    def __repr__(self):
        return self.panelinfo

    def __str__(self):
        return "%s: state=%s" % (self.name, self.state)

